﻿/***********************************************************************
 *            Project: CoreCms.Net                                     *
 *                Web: https://CoreCms.Net                             *
 *        ProjectName: 核心内容管理系统                                *
 *             Author: 大灰灰                                          *
 *              Email: JianWeie@163.com                                *
 *         CreateTime: 2020-05-12 0:54:53
 *        Description: 暂无
 ***********************************************************************/


using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;

namespace CoreCms.Net.Utility.Helper
{
    /// <summary>
    /// 模拟标准表单Post提交
    /// </summary>
    public static class HttpHelper
    {
        private static readonly HttpClient client = new HttpClient();
        public static string GetUrl(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "application/json";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }

        #region POST-JSON  
        /// <summary>
        /// http Post请求 发送Json数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="headht"></param>
        /// <returns></returns>
        public static string PostJson(string url, string postData, Hashtable headht = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json;charset=UTF-8";
            request.Accept = "application/json";

            #region headers设置
            if (headht != null)
            {
                foreach (DictionaryEntry item in headht)
                {
                    request.Headers.Add(item.Key.ToString(), item.Value.ToString());
                }
            }
            #endregion

            byte[] paramJsonBytes;
            paramJsonBytes = System.Text.Encoding.UTF8.GetBytes(postData);
            request.ContentLength = paramJsonBytes.Length;
            Stream writer;
            try
            {
                writer = request.GetRequestStream();
            }
            catch (Exception)
            {
                writer = null;
                Console.Write("连接服务器失败!");
            }
            writer.Write(paramJsonBytes, 0, paramJsonBytes.Length);
            writer.Close();
            HttpWebResponse response;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
            }
            Stream resStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(resStream);
            string text = reader.ReadToEnd();
            return text;
        }
        #endregion
        /// <summary>
        /// 模拟标准表单Post提交
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postdate"></param>
        /// <returns></returns>
        public static string PostSend(string url, string postdate)
        {
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            myHttpWebRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            myHttpWebRequest.Method = "POST";
            Stream myRequestStream = myHttpWebRequest.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream);
            myStreamWriter.Write(postdate);
            myStreamWriter.Flush();
            myStreamWriter.Close();
            myRequestStream.Close();

            HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
            Stream myResponseStream = myHttpWebResponse.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            String outdata = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return outdata;
        }
        //http post请求
        public static async Task<string> HttpPostAsync(string url, Dictionary<string, string> parameters)
        {
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
            parameters["Content-Type"] = "application/json";
            request.Content = JsonContent.Create(parameters);
            //request.Headers.Add("Content-Type", "application/json");
            //string json = JsonConvert.SerializeObject(parameters);
            //// 将JSON数据作为请求体  
            //request.Content = new StringContent(json, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.SendAsync(request);
            // 检查响应是否成功  
            if (response.IsSuccessStatusCode)
            {
                // 读取响应内容  
                string responseBody = await response.Content.ReadAsStringAsync();
                //Console.WriteLine(responseBody);
                return responseBody;
            }
            throw new Exception("请求失败");
        }


        //获取服务器时间戳
        public static async Task<string> HttpGetAsync(string url)
        {
            HttpResponseMessage response = await client.GetAsync(url);
            // 检查响应是否成功  
            if (response.IsSuccessStatusCode)
            {
                // 读取响应内容  
                string responseBody = await response.Content.ReadAsStringAsync();
                //Console.WriteLine(responseBody);
                return responseBody;
            }
            throw new Exception("请求失败");
        }
    }
}
